var express = require('express');
var router = express.Router();
const { Course,Category,User } = require('../../models');
const { Op } = require('sequelize');

const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;


        const condition = {
            ...getCondition(),
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize
        }
        if (query.UserId) {
            condition.where = {
                UserId: {
                    [Op.eq]: query.userId
                }
            }
        }

        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            }
        }
        if (query.recommended) {
            condition.where = {
                recommended: {
                    [Op.eq]: query.recommended === 'true'
                }
            }
        }
        if (query.introductory) {
            condition.where = {
                introductory: {
                    [Op.eq]: query.introductory === 'true'
                }
            }
        }
        const { count, rows } = await Course.findAndCountAll(condition);
        success(
            res,
            '查询课程列表成功',
            {
                course: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询课程详情
router.get('/:id', async function (req, res, next) {
    try {
        const course = await getCourse(req);
        success(
            res,
            '查询课程成功',
            {course}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 新建课程
router.post('', async function (req, res, next) {
    try {
        const body = filterBody(req.body)
        body.userId = req.user.id;
        const course = await Course.create(body)
        success(
            res,
            '创建课程成功',
            {course}
        )
    } catch (error) {
        failure(res, error)
    }
});

// 删除课程
router.delete('/:id', async function (req, res, next) {
    try {
        const course = await getCourse(req);
        await course.destroy()
        success(
            res,
            '删除课程成功'
        )
    } catch (error) {
        failure(res, error)
    }
});

// 更新课程
router.put('/:id', async function (req, res, next) {
    try {
        const course = await getCourse(req);
        const body = filterBody(req.body)
        await course.update(body)
        success(
            res,
            '更新课程成功', {
                course
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 name
const filterBody = (body)=>{
    return {
        categoryId: body.categoryId,
        // userId: body.userId,
        name: body.name,
        image: body.image,
        recommended: body.recommended,
        introductory: body.introductory,
        content: body.content,
    }
}

const getCondition = () => {
    return {
        attributes: { exclude: ['CategoryId', 'UserId'] },
        include: [
            { model: Category, as: 'category', attributes: ['id', 'name'] },
            { model: User, as: 'user', attributes: ['id', 'username', 'avatar'] },
        ]
    }
}

/**
 * 查询当前课程
 * @param {*} req 
 */
async function getCourse(req) {
    const { id } = req.params;
    const condition = getCondition();
    const course = await Course.findByPk(id,condition);
    if (!course) {
        throw new NotFoundError(`ID: ${id}的课程未找到`)
    }
    return course;
}

module.exports = router;
